/*
    nspire-gamekit - a simple homebrew game framework
    Copyright (C) 2011  Daniel Tang

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <os.h>
#include "nimg.h"
#include "screen.h"

#define MAGIC_STR "NIMG"

NGKScreenBuffer* screenBufferFromFile(const char* nimg) {
    FILE* spriteFile = fopen(nimg, "rb");
    char magicNumber[4];
    uint16_t endianCheck;
    uint32_t width;
    uint32_t height;
    NGKScreenBuffer* buffer = NULL;
    
    if (!spriteFile) {
        return NULL;
    }
    
    fread(&magicNumber, 1, 4, spriteFile);
    fread(&endianCheck, 2, 1, spriteFile);
    fread(&width, 4, 1, spriteFile);
    fread(&height, 4, 1, spriteFile);
    
    if (memcmp(&magicNumber, MAGIC_STR, 4) != 0) 
    { goto finish; }
    
    if (endianCheck != 0xFF) { //Laziest way to solve endian issues I swear
        width = bswap32(width);
        height = bswap32(height);
    }
    
    buffer = screenBufferAlloc(NGKSizeMake(width, height));
    if (!buffer) goto finish;
    
    fread(screenBufferData(buffer), 1, width*height, spriteFile);
    
    finish:
    fclose(spriteFile);
    return buffer;
}